package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.system.api.RemotePostService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.validator.QueryHelpMybatisPlus;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.SysLogPerm;
import cn.cdeden.knowledge.domain.dto.SysLogPermDto;
import cn.cdeden.knowledge.domain.dto.SysLogPermQueryParam;
import cn.cdeden.knowledge.enums.PermTypeEnum;
import cn.cdeden.knowledge.enums.TreeEnum;
import cn.cdeden.knowledge.mapper.SysLogPermMapper;
import cn.cdeden.knowledge.service.SysLogPermService;
import cn.cdeden.knowledge.service.TeamRoleService;
import cn.cdeden.system.api.RemoteDeptService;
import cn.cdeden.system.api.RemoteRoleService;
import cn.cdeden.knowledge.utils.PageUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* @author GW
* @date 2024-01-19
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = SysLogPermService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SysLogPermServiceImpl extends ServiceImpl<SysLogPermMapper, SysLogPerm> implements SysLogPermService {

    // private final RedisUtils redisUtils;
    private final SysLogPermMapper sysLogPermMapper;
    private final TeamRoleService teamRoleService;
    @DubboReference(check = false)
    private final RemoteDeptService sysDeptService;
    @DubboReference(check = false)
    private final RemoteRoleService sysRoleService;
    @DubboReference(check = false)
    private final RemotePostService remotePostService;

    @Override
    public TableDataInfo<SysLogPermDto> queryAll(SysLogPermQueryParam query, Pageable pageable) {
        IPage<SysLogPerm> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<SysLogPerm> page = sysLogPermMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        TableDataInfo<SysLogPerm> build = TableDataInfo.build(page);
        TableDataInfo<SysLogPermDto> sysLogPermDtoTableDataInfo = MapstructUtils.convertTableDataInfo(build, SysLogPermDto.class);
//        PageInfo<SysLogPermDto> sysLogPermDtoPageInfo = ConvertUtil.convertPage(page, SysLogPermDto.class, pageable);
        for (SysLogPermDto sysLogPermDto : sysLogPermDtoTableDataInfo.getRows()) {
            if (sysLogPermDto.getType().equals(TreeEnum.TEAM.getType())){
                sysLogPermDto.setTeamRoleName(teamRoleService.getById(sysLogPermDto.getTeamRoleId()).getRoleName());
            }
            int objectType = sysLogPermDto.getObjectType();
            //根据类型放入对象名称
            if (objectType == PermTypeEnum.USER.getPermTypeCode()) {
                //用户类型
                sysLogPermDto.setObjectName(LoginHelper.getLoginUserByUserId(Long.valueOf(sysLogPermDto.getObjectId())).getNickname());
            }
            if (objectType == PermTypeEnum.DEPT.getPermTypeCode()) {
                //部门类型
                sysLogPermDto.setObjectName(sysDeptService.getById(Long.valueOf(sysLogPermDto.getObjectId())).getDeptName());
            }
            if (objectType == PermTypeEnum.ROLE.getPermTypeCode()) {
                //系统角色类型
                sysLogPermDto.setObjectName(sysRoleService.getById(Long.valueOf(sysLogPermDto.getObjectId())).getRoleName());
            }
            if (objectType == PermTypeEnum.JOB.getPermTypeCode()) {
                //岗位类型
                sysLogPermDto.setObjectName(remotePostService.getById(Long.valueOf(sysLogPermDto.getObjectId())).getName());
            }
        }
        return sysLogPermDtoTableDataInfo;
    }

    @Override
    public List<SysLogPermDto> queryAll(SysLogPermQueryParam query){
        return MapstructUtils.convert(sysLogPermMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), SysLogPermDto.class);
    }

    @Override
    public SysLogPerm getById(Long id) {
        return sysLogPermMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public SysLogPermDto findById(Long id) {
        return MapstructUtils.convert(getById(id), SysLogPermDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(SysLogPermDto resources) {
        SysLogPerm entity = MapstructUtils.convert(resources, SysLogPerm.class);
        return this.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertBatch(List<SysLogPerm> resources) {
        return this.saveBatch(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(SysLogPermDto resources){
        SysLogPerm entity = MapstructUtils.convert(resources, SysLogPerm.class);
        boolean ret = this.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(Set<Long> ids){
        // delCaches(ids);
        if(ids==null||ids.size()==0)baseMapper.delete(null);
        return this.removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id){
        Set<Long> set = new HashSet<>(1);
        set.add(id);
        return this.deleteByIds(set);
    }

    /*
    private void delCaches(Long id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Long> ids) {
        for (Long id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<SysLogPermDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (SysLogPermDto sysLogPerm : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("用户", sysLogPerm.getUserId());
              map.put("权限", sysLogPerm.getPerm());
              map.put("创建编号", sysLogPerm.getCreateId());
              map.put("创建者", sysLogPerm.getCreateBy());
              map.put("创建日期", sysLogPerm.getCreateTime());
              map.put("日志id", sysLogPerm.getLogId());
              map.put("类型", sysLogPerm.getType());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/
}
